const _sys_app = module.exports
const jwt = require('../../../framework/lib/jwt')

// jwt 验证
_sys_app.check = async (token) => {
    let payload = null
    if (!token) throw new Error('token is empty!')

    try {
        payload = jwt.decode(token, '', true)
    } catch (e) {
        throw new Error(e.message)
    }

    if (!payload['iss']) {
        throw new Error('iss is required')
    }

    let sysApp = await dbUtil.getRow('sys_app@iothub_platform', { app_key: payload['iss'] })
    if (!sysApp) {
        throw new Error('app not found')
    }

    try {
        // 验证签名是否正确
        payload = jwt.decode(token, sysApp.app_secret, false)
    } catch (e) {
        throw new Error(e.message)
    }

    // 客户端连接验证user_id
    if (sysApp['app_name'].split('_').length > 1 && !payload['user_id']) {
        throw new Error('user_id is required')
    }

    return { ...payload, ...sysApp }
}
